<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Repositories\QuizRepository;
use App\Models\Quiz;

/**
 * 开奖(队列)
 *
 * Class ProcessAnnounce
 * @package App\Jobs
 */
class ProcessAnnounce implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $quiz;

    public $tries = 1;

    public $timeout = 1800;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(Quiz $quiz)
    {
        $this->quiz = $quiz;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $start = microtime(true);
        $quiz = $this->quiz->force();
        if ($quiz->status != QuizRepository::QUIZ_STATUS_PROCESSING) {
            throw new \Exception('quiz status is not processing');
        }
        $quiz->items()->with('processedBets')->get()->each(function ($item) {
            // 竞猜内容结果为空提示错误
            if (empty($item->result)) {
                throw new \Exception('quiz item result is empty');
            }
            $item->processedBets->each(function ($bet) use ($item) {
                // 玩家结算
                QuizRepository::settlementForPlayer($bet, $item);
            });
        });

        // 庄家结算
        QuizRepository::settlementForCreater($quiz);

        dump(sprintf('id: %d  used: %f', $quiz->id, microtime(true) - $start));
    }

    /**
     * @param \Exception $exception
     */
    public function failed(\Exception $exception)
    {
        Log::debug($exception->getMessage());
    }
}
